<template>
  <div style="width: 100%; height: 100%; overflow:hidden">
    <div id="map" style="width: 100%; height: 100vh;position: absolute;top: 0;left: 0; z-index: 1;">

    </div>
    <div @click="show=true" style="position: absolute;right: 5px;top: 5px;z-index: 1000;background-color: #f90;width: 40px;height: 40px;text-align: center;border-radius: 5px;">
      <img src="../../static/mark.png" style="margin:5px;display: block; width: 30px;height: 30px;" />
    </div>



    <van-overlay :show="show" @click="show = false" >
      <div style="background-color: white;border-radius: 10px;width: 80vw;min-height: 30vh;margin-left: 10vw;margin-top: 30vh;">
        <div style="width: 100%;text-align: center;height: 60%;line-height: 18vh">
          请确认养殖场空间位置是否正确
        </div>
        <div style="width: 100%;height: 40%;display: flex;align-content: center;flex-direction: row;justify-content:space-around">
          <div class="info btn" @click="confirm">
            是
          </div>
          <div class="danger btn" @click="notConfirm">
            否
          </div>
        </div>
      </div>

    </van-overlay>


<!--    <van-dialog v-model="show"  confirmButtonColor="#FF0000"  cancelButtonText="✖ 否" confirmButtonText="✔ 是" show-cancel-button closeOnClickOverlay @confirm=""  @cancel="">-->
<!--    -->
<!--    </van-dialog>-->
    <div style="position: absolute;width: 100%;padding-left: 10px;bottom: 0px;z-index: 1000;background-color: rgba(0,0,0,0.3);">
      <!--地图级别-->
      <van-row>
        <van-col span="11"><span style="color: #fff;">东经：{{lon}}</span></van-col>
        <van-col span="5"><span style="color: #fff;">级别</span></van-col>
        <van-col span="8"><span style="color: #fff;">{{qhmc}}</span></van-col>
      </van-row>
      <van-row>
        <van-col span="11"><span style="color: #fff;">北纬：{{lat}}</span></van-col>
        <van-col span="5"><span style="color: #fff;">{{level}}</span></van-col>
        <van-col span="8"><span style="color: #fff;">{{qhdm}}</span></van-col>
      </van-row>
    </div>
  </div>
</template>

<script>
  import api_user from "../api/api_user.js"
  import Cookies from "js-cookie";
  import Turf from "turf";
  import mapboxgl from "mapbox-gl";
  import layerSrc from "../config/layer_identify.js"
  import dingwei from "../assets/dingwei.png"

  import {
    Notify
  } from 'vant';


  export default {
    name: 'HelloWorld',
    data() {
      return {
        level: 0,
        lat: 0,
        lon: 0,
        qhdm: "",
        qhmc: "",
        map: null,
        show: false,
        farmId: null,
        isConfirm: 0,
      }
    },
    async mounted() {
      try {
        Cookies.remove("token");
        let sign = await api_user.getSignature({
          key: "fcd26b3e659742c4acf692f14eff9bbd",
          secret: "7ab024e62976450fb980899754ac2083"
        });
        if (sign && sign.success) {
          let result = sign.result;
          Cookies.set("token", result);
          Notify({
            type: 'success',
            message: '应用认证成功'
          });
        } else {
          throw Error('应用认证失败');
        }

      } catch (e) {
        // 危险通知
        Notify({
          type: 'danger',
          message: '应用认证失败'
        });
      } finally {
        this.initMap()
      }
    },
    methods: {
      iniTArea() {
        this.farmId = this.getQueryString("farmId") || null;

        if (!this.farmId) {
          // 危险通知
          Notify({
            type: 'danger',
            message: '无法获取养殖场信息'
          });
          return;
        }
        api_user.getLocation({
          farmId: this.farmId
        }).then(res => {
          console.log(res);
          if (res && res.code == 0) {
            this.addPolygon(res.data.geoJsonShape,res.data.farmName);
          } else {
            throw new Error()
          }
        }).catch(e => {
          console.log(e)
          Notify({
            type: 'danger',
            message: '获取养殖场信息失败'
          });
        })

      },
      addPolygon(geoJson,name) {
        let box = Turf.bbox(JSON.parse(geoJson));
        let center = Turf.center(JSON.parse(geoJson));
        console.log(center)
        this.map.fitBounds([
          [box[0], box[1]],
          [box[2], box[3]]
        ], {
          padding: {
            top: 100,
            bottom: 100,
            left: 0,
            right: 0
          }
        }); //设置地图定位范围
        this.map.addSource('maine', {
          'type': 'geojson',
          'data': {
            'type': 'Feature',
            'geometry': JSON.parse(geoJson)
          }
        });
        this.map.addLayer({
          'id': 'maine',
          'type': 'line',
          'source': 'maine',
          'layout': {},
          'paint': {
            'line-color': '#FF0',
            'line-width': 2
          }
        });
        let that=this;
        this.map.loadImage(
          dingwei,
          function(error, image) {
            if (error) throw error;
            that.map.addImage('cat', image);
            that.map.addSource('point', {
              'type': 'geojson',
              'data': {
                'type': 'FeatureCollection',
                'features': [center]
              }
            });
            that.map.addLayer({
              'id': 'points',
              'type': 'symbol',
              'source': 'point',
              'layout': {
                'icon-image': 'cat',
                'icon-size': 0.2
              }
            });
          }
        );
        new mapboxgl.Popup({ closeOnClick: false,closeButton:false })
        .setLngLat(center.geometry.coordinates)
        // .setLngLat(center)
        .setHTML('<h3>'+name+'</h3>')
        .addTo(this.map);
        console.log(center.geometry.coordinates)
      },
      getQueryString: function(variable) {
        let url = decodeURI(window.location.href);
        if (url.indexOf('?') == -1) {
          return;
        }
        let array = url.split('?');
        let query = array[1];
        let vars = query.split('&');
        for (let i = 0; i < vars.length; i++) {
          let pair = vars[i].split('=');
          if (pair[0] == variable) {
            return pair[1];
          }
        }
        return (false);
      },
      returnClick() {
        //打包数据，发送给小程序接收区
        let postData = {
          isConfirm: this.isConfirm
        };
        uni.postMessage({
          data: JSON.stringify(postData)
        });
        // uni.navigateBack({
        //   delta: 1
        // });
        // wx.miniProgram.navigateTo({
        //   url: '../login/login'
        // })
      },
      confirm() {
        console.log("确认")
        this.show = false;
        this.isConfirm = 1;
        this.returnClick();
      },
      notConfirm() {
        console.log("取消")
        this.show = false;
        this.isConfirm = 2;
        this.returnClick();
      },
      initMap() {
        // mapboxgl.accessToken =
        //   'pk.eyJ1IjoiaGFtYnVnZXJkZXZlbG9wIiwiYSI6ImNqNXJtZjF4ZzB3em4yd21pZmVqbHlleDAifQ.I9eqVjtotz7jaU7XcJm9pQ';
        let map = new mapboxgl.Map({
          container: "map",
          style: "http://gykj123.cn:9035/api/v1/styles/gykj/ryFyQme9r",
          maxZoom: 17.99,
          zoom: 14,
          center: [111.929173, 32.67442],
          dragRotate: false,
          pitchWithRotate: false,
          touchZoomRotate: true,
          refreshExpiredTiles: true,
          transformRequest: (url, resourceType) => {
            if (
              url.includes("mse.gykj.com.cn") ||
              url.includes("mse.agribigdata.com.cn")
            ) {
              return {
                url: url,
                headers: {
                  Signature: Cookies.get('token')
                },
              };
            } else {
              return {
                url: url,
              };
            }
          },
        });
        this.map = map;
        //解决canvas渲染不正确
        map.on("styledata", function() {
          map.resize();
        });
        map.on("load", (e) => {
          //禁止旋转
          map.touchZoomRotate.disableRotation();
          map.dragRotate.disable();
          this.level = map.getZoom().toFixed(2);
          this.lon = map.getCenter().lng.toFixed(6);
          this.lat = map.getCenter().lat.toFixed(6);


          for (let i = 0; i < layerSrc.layer_Drilldown.length; i++) {
            let lyrDrl = layerSrc.layer_Drilldown[i];
            //1增加透明的fill图层用于查询
            if (!map.getLayer(lyrDrl.layer_fill + "_search")) {
              map.addLayer({
                "id": lyrDrl.layer_fill + "_search",
                "type": "fill",
                "source": lyrDrl.sourceId,
                "source-layer": lyrDrl.sourceLayer,
                "minzoom": lyrDrl.minzoom,
                "maxzoom": lyrDrl.maxzoom,
                "layout": {},
                "paint": {
                  "fill-opacity": 0.0,
                },
              });
            } else {
              /*add by gf 20190123  由于定制地图将这些用于查询的图层visibility设置为隐藏，不能做查询，这里在用到的时候将visibility设置为可见 */
              map.setLayoutProperty(lyrDrl.layer_fill + "_search", "visibility", "visible");
            }
          }


          this.calCenterAdminArea();
          //实时级别、中心点
          map.on('drag', this.mapDrag);
          map.on('zoomend', this.mapZoomEnd);
          map.on('moveend', this.mapMoveEnd);
          this.iniTArea();
        });

      },
      mapDrag: function() {
        this.lon = this.map.getCenter().lng.toFixed(6);
        this.lat = this.map.getCenter().lat.toFixed(6);
      },
      mapZoomEnd: function() {
        this.level = this.map.getZoom().toFixed(2);
        this.lon = this.map.getCenter().lng.toFixed(6);
        this.lat = this.map.getCenter().lat.toFixed(6);

        this.calCenterAdminArea()
      },
      mapMoveEnd: function() {
        //更新中心点落入的行政区划信息
        this.calCenterAdminArea()
      },
      calCenterAdminArea() {
        let map = this.map
        let centPt = map.project(map.getCenter());

        let features = map.queryRenderedFeatures(centPt); //查询点击的要素

        let tempLvl = 6; /*一共六个级别*/
        let resLevel = -1;
        let res = null; /*最终结果*/
        features.forEach(feature => { /*查找当前遍历元素对应的配置数据*/
          let lyrDrl = layerSrc.layer_Drilldown.find(lyr => {
            return feature.layer.source === lyr.sourceId
          });
          if (lyrDrl && lyrDrl.level <= tempLvl) {
            resLevel = lyrDrl.level;
            res = feature;
          }
        });

        this.qhmc = res ? res.properties.qhmc : "";
        this.qhdm = res ? res.properties.qhdm : "";

      },
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .btn{
    height: 44px;
    width: 80px;
    line-height: 44px;
    text-align: center;
    border-radius: 3px;
    color: #fff;

  }
.info{
  background-color: #1989fa;
  border: 1px solid #1989fa;
}
  .danger{
    background-color: #ee0a24;
    border: 1px solid #ee0a24;
  }
</style>
